package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"vehicle-mgr/cache"
	"vehicle-mgr/models"
	"vehicle-mgr/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "数据不能为空",
		})
		return
	}

	var user models.User
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Find(&user).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询用户失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 200,
				"msg":  "密码错误三次,禁止登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{

		Uid: uid,
		Rid: rid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "新增失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "新增成功",
	})
	return
}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{

		Nid: nid,
		Rid: rid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "新增失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "新增成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
	*/
	var userRole []models.Role

	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid=?", uid).
		Find(&userRole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": userRole,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
	*/
	var roleNode []models.Node

	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": roleNode,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var user []models.User
	redis_key := c.PostForm("list_") + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": user,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var user models.User
	redis_key := c.PostForm("detail") + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": user,
	})
	return

}
